#coding=utf-8
#author:dn_李四海(qq:653378495)
#动脑学院VIP
'''
1.自定义一个异常类,当list内元素长度超过10的时候抛出异常
'''
import sys
# a_list=[1,2,3,4,5,6,7,8,9,10,11]
# class MyError(IndexError):
#     def __init__(self,value):
#         self.value = value
#     def __str__(self):
#         return repr(self.value)
# try:
#     if len(a_list)>10:
#         raise MyError("索引异常")
# except IndexError as e:
#     print(e)
'''
2.思考如果对于多种不同的代码异常情况都要处理,又该如何
    去处理,自己写一个小例子
'''
# try:
#    u = 7 / int('iiii')
#    m = 9 / 3
#    print(open('hello.txt'))
# except NameError as l:
#    print(l)
#    print('变量名错误')
# except ZeroDivisionError as o:
#    print(o)
#    print('被0除了')
# except SyntaxError as p:
#    print(p)
#    print('语法错误')
# except IndentationError as k:
#    print(k)
#    print('索引错误')
# except IOError as h:
#    print(h)
#    print('输入输出错误')
# except ArithmeticError as t:
#    print(t)
#    print('属性异常')
# except Exception as g:
#    print(g)
#    print('这个错误不在计算内')
# else:
#    print('计算内:)')
# finally:
#    print('计算完毕')
'''
3.try-except和try-finally有什么不同,写例子理解区别
'''
# try:
#     fp =open('null.txt','r')
# except:  ##发生异常执行except
#     print ('open error')
# finally: ##无论如何都执行
#     print ('end')
'''
4.写函数，检查传入字典的每一个value的长度，如果大于2，
    那么仅仅保留前两个长度的内容，并将新内容返回给调用者
    dic = {“k1”: "v1v1","k2":[11,22,33}}
'''
def get_two_value(value):
    two_value = {}
    count = 0
    for i,v in value.items():
        if count >=2:
            break
        two_value[i] =v
        count += 1
    return two_value

def check_dic(dic):
    #判断是否是字典
    if not isinstance(dic,dict):
        raise TypeError('输入的参数不是字典，程序暂停')
    result = {}
    #判断长度
    for index,value in dic.items():
        if len(value) <= 2:
            result[index] = value
        elif isinstance(value,(str,list,tuple)):
            result[index] = value[:2]
        elif isinstance(value,(dict,set)):
            result[index] = get_two_value(value)
    return result
def question_04():
    try:
        dic = {"k1": "v1v1", "k2": [11, 22, 33]}
        print(check_dic(dic))
    except Exception as e:
        traceback.print_exc()
def main():
    question_04()
if __name__ == '__main__':
    main()